package com.sixbro.authorization.security.component;

import com.sixbro.common.constant.AuthConstants;
import com.sixbro.authorization.security.domain.OAuth2UserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Map;

/**
 * <p>
 *  1. 自定义token解析器，从jwt token中解析用户信息。
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 14:08
 */
public class AdditionalUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    /**
     * 重写抽取用户数据方法
     *
     * @param map   用户认证信息
     * @return
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
            Long id = Long.parseLong(map.get(AuthConstants.DETAILS_USER_ID_KEY).toString());
            String username = (String) map.get(USERNAME);
            String mobile = (String) map.get(AuthConstants.DETAILS_MOBILE_KEY);
            String tenantId = (String) map.get(AuthConstants.DETAILS_TENANT_ID_KEY);
            OAuth2UserDetails user = new OAuth2UserDetails(id, mobile, tenantId, username, "N/A", authorities);
            return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
        }
        return null;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
}